/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import {
  pickedFaceData,
  pickedLineData,
  pickedVertexData,
  pickedModelData,
} from '@amcax/base';
import { previewer } from '@app-cad/module';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useTools } from '@app-cad/common/hooks/useTools';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import { isEmpty } from 'lodash';
import { useEffect, useState } from 'react';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { wsApi } from '@app-cad/server';
import { getIdOfPickedObj } from '@app-cad/common/utils/render';
import { ChildLineCommandProps } from './type';

type pickedALLType = pickedFaceData | pickedLineData | pickedVertexData;

type FormDataType = {
  obj: pickedALLType[];
  frame: pickedModelData;
  distanceX: number;
  distanceY: number;
  distanceZ: number;
  keepSrc: boolean;
};

export function MoveFrame({
  onClose,
  props,
  editDxid,
  base,
}: ChildLineCommandProps) {
  const { picker } = useTools();

  const initData = {
    obj: undefined,
    frame: null,
    distanceX: 1,
    distanceY: 1,
    distanceZ: 1,
    keepSrc: true,
  };

  const [formData, setFormData] = useState<FormDataType>(initData);

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props) {
      const obj = props?.params?.base;
      const frame = props?.params?.frame;
      const keepSrc = props?.params?.keepSrc;
      await initEditDependency([obj, frame]);
      const defaultObj = obj
        ? (picker.generatePickObjByPickID(obj) as pickedALLType)
        : undefined;
      const defaultFrame = frame
        ? (picker.generatePickObjByPickID(frame) as pickedModelData)
        : undefined;
      setFormData({
        obj: [defaultObj],
        frame: defaultFrame,
        distanceX: props?.params?.distanceX,
        distanceY: props?.params?.distanceY,
        distanceZ: props?.params?.distanceZ,
        keepSrc: keepSrc,
      });
    } else {
      const defaultObj = base
        ? (picker.generatePickObjByPickID(base) as pickedALLType)
        : undefined;
      setFormData({
        ...initData,
        ...(defaultObj ? { obj: [defaultObj] } : {}),
      });
    }
  }, [editDxid, base]);

  const preview = async () => {
    if (props) {
      previewer.clear();
    } else {
      clear();
    }

    const { obj, distanceX, distanceY, distanceZ } = formData;
    if (
      isEmpty(obj) ||
      distanceX === null ||
      distanceY === null ||
      distanceZ === null
    ) {
      return;
    }

    await execute(true);
  };

  const checkAndFinishDraw = async () => {
    const { obj, distanceX, distanceY, distanceZ } = formData;
    if (
      isEmpty(obj) ||
      distanceX === null ||
      distanceY === null ||
      distanceZ === null
    ) {
      return;
    }

    await execute(false);
    onClose();
  };

  const execute = async (preview: boolean) => {
    const { obj, frame, distanceX, distanceY, distanceZ, keepSrc } = formData;
    const params = {
      mode: 'frame',
      frame: getIdOfPickedObj(frame),
      distanceX: distanceX,
      distanceY: distanceY,
      distanceZ: distanceZ,
      keepSrc: keepSrc,
    };

    if (editDxid) {
      const res = await wsApi.setParams(editDxid, params, preview);
      if (preview) {
        previewInCommand(res);
      }
    } else {
      await confirmCommand(
        {
          o: obj.map((i) => getIdOfPickedObj(i)),
          a: params,
        },
        preview,
      );
    }
  };

  const isFormDataValid = () => {
    const { obj, distanceX, distanceY, distanceZ, keepSrc } = formData;
    return (
      obj !== null &&
      distanceX !== null &&
      distanceY !== null &&
      distanceZ !== null &&
      keepSrc !== null
    );
  };

  const {
    initEditDependency,
    initingEdit,
    clear,
    confirmCommand,
    isLoading,
    previewInCommand,
  } = useCommand('cmd-move-frame', {
    commandName: 'Translation',
    editDxid: editDxid || props?.shape,
    onClose,
    finishDraw: checkAndFinishDraw,
  });

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      obj: {
        type: 'array',
        items: {
          type: 'string',
          enum: [],
        },
        format: PickInputRJSFFormat.MultiPickALL,
        uniqueItems: true,
      },
      distanceX: {
        type: 'number',
        title: 'X偏移',
        default: 1,
        format: NumberInputFormat.Length,
      },
      distanceY: {
        type: 'number',
        title: 'Y偏移',
        default: 1,
        format: NumberInputFormat.Length,
      },
      distanceZ: {
        type: 'number',
        title: 'Z偏移',
        default: 1,
        format: NumberInputFormat.Length,
      },
      frame: {
        type: 'string',
        format: PickInputRJSFFormat.PickFrame,
      },
      keepSrc: {
        type: 'boolean',
        title: '显示初始元素',
        default: true,
      },
    },
  };

  return (
    <NonDialogPickableCommandForm
      disabled={initingEdit}
      submitLoading={isLoading}
      onCancel={onClose}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        setFormData({
          obj: v?.obj,
          frame: v.frame,
          distanceX: v.distanceX,
          distanceY: v.distanceY,
          distanceZ: v.distanceZ,
          keepSrc: v.keepSrc,
        });
      }}
      extraUiSchema={{
        obj: {
          'ui:placeholder': '请输入元素',
          'ui:autofocus': !editDxid,
          'ui:disabled': !!editDxid,
        },
        distanceX: {
          'ui:placeholder': '请输入X偏移量',
          'ui:autofocus': !!editDxid,
        },
        distanceY: {
          'ui:placeholder': '请输入Y偏移量',
        },
        distanceZ: {
          'ui:placeholder': '请输入Z偏移量',
        },
        frame: {
          'ui:placeholder': '请输入参考坐标系，默认初始坐标系',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
}
